package com.pithypan.controller;

import com.pithypan.common.Constants;
import com.pithypan.common.utils.R;
import com.pithypan.dto.SessionWebUserDto;
import com.pithypan.entity.FileShare;
import com.pithypan.service.FileShareService;
import com.pithypan.vo.FileShareQuery;
import com.pithypan.vo.PaginationResultVo;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.w3c.dom.UserDataHandler;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

/**
 * 文件分享
 */
@RestController
@RequestMapping("/share")
public class FileShareController {

    @Resource
    private FileShareService fileShareService;


    /**
     * 分享文件分页查询
     * @param session
     * @param query
     * @return
     */
    @RequestMapping("/loadShareList")
    public R loadShareList(HttpSession session, @RequestBody FileShareQuery query) {
        //从session中获取登陆用户信息
        SessionWebUserDto userDto = (SessionWebUserDto) session.getAttribute(Constants.SESSION_KEY);
        query.setUserId(userDto.getUserId());
        query.setQueryFileName(true);           //是否关联file_info表查询文件名
        query.setOrderBy("share_time desc");    //根据分享时间降序排序

        PaginationResultVo result = fileShareService.findListByPage(query);
        return R.ok().data("shareList", result);
    }


    /**
     * 文件分享
     * @param session
     * @param fileId
     * @param validType
     * @param code
     * @return
     */
    @RequestMapping("/shareFile")
    public R shareFile(HttpSession session, String fileId, Integer validType, String code){
        //从session中获取登陆用户信息
        SessionWebUserDto userDto = (SessionWebUserDto) session.getAttribute(Constants.SESSION_KEY);
        FileShare share = new FileShare();
        share.setUserId(userDto.getUserId());
        share.setFileId(fileId);
        share.setValidType(validType);
        share.setCode(code);

        fileShareService.saveShare(share);
        return R.ok().data("share", share);
    }


    /**
     * 取消分享文件
     * @param session
     * @param shareIds    shareId,shareId...
     * @return
     */
    @RequestMapping("/cancelShare")
    public R cancelShare(HttpSession session, String shareIds) {
        //从session中获取登陆用户信息
        SessionWebUserDto userDto = (SessionWebUserDto) session.getAttribute(Constants.SESSION_KEY);
        fileShareService.deleteFileShareBatch(shareIds.split(","), userDto.getUserId());
        return R.ok();
    }


}
